import re

import requests
from lxml import etree

from base.utils.StringUtil import StringUtil
from base.utils.TimeUtil import TimeUtil
from base.utils.UrlUtil import UrlUtil
from models.book import BookInfo


def get_book(book_title):
    search_url = 'https://www.douban.com/search?cat=1001&q=' + book_title
    response = requests.get(search_url, headers=UrlUtil.get_headers())
    html = etree.HTML(response.text)
    book_urls = html.xpath('//*[@id="content"]/div/div[1]/div[3]/div[2]/div[1]/div[2]/div/h3/a/@href')
    if book_urls is None or len(book_urls) <= 0:
        assert Exception("找不到书籍")
    for book_url in book_urls:
        TimeUtil.middle_sleep()
        # 进入书籍的详情页
        response = requests.get(book_url, headers=UrlUtil.get_headers())
        html = etree.HTML(response.text)
        # 获取标题
        title = html.xpath('//span[contains(@property,"itemreviewed")]/text()')[0].strip()
        edit_distance = StringUtil.edit_distance(title, book_title)
        print('title: ', title, '与 book_name: ', book_title, '的编辑距离为', round(edit_distance, 2))
        if edit_distance > 0.6:
            continue
        # 获取作者名
        authors = html.xpath('//*[@id="info"]/span[contains(text(),"作者")]/following::a[1]/text()')
        author = authors[0].strip() if len(authors) > 0 else None
        if author is not None:
            author = re.sub(' +', ' ', author).replace('\n', '')
        # 获取原作名
        src_title = html.xpath('//*[@id="info"]/span[contains(text(),"原作名")]/following::text()[1]')
        if src_title is not None and len(src_title) > 0:
            src_title = src_title[0].strip()
        else:
            src_title = ""
        # 获取评分
        score = html.xpath('//*[@id="interest_sectl"]/div/div[2]/strong/text()')[0].strip()
        if len(score) == 0:
            score = '0'
        # 获取评价人数
        eval_number = html.xpath('//*[@id="interest_sectl"]/div/div[2]/div/div[2]/span/a/span/text()')
        if len(eval_number) > 0:
            eval_number = eval_number[0].strip()
        else:
            eval_number = '0'
        # 获取内容介绍
        book_intro_list = html.xpath(
            '//span[@class="all hidden"]//div[@class="intro"]//p/text()')
        if book_intro_list is None or len(book_intro_list) <= 0:
            book_intro_list = html.xpath(
                '//div[@id="link-report"]//div[@class="intro"]//p/text()')
        book_intro = '\n'.join(book_intro_list)
        print(book_intro_list)
        # 获取作者介绍
        author_intro_list = html.xpath(
            '//span[contains(text(),"作者简介")]/following::div[1]//div[@class="intro"]//p/text()')
        author_intro = '\n'.join(author_intro_list)
        # 获取标签
        tags = html.xpath('//*[@id="db-tags-section"]/div/span/a/text()')
        tags = '##'.join(tags)

        # 获取封面
        cover_url = html.xpath('//*[@id="mainpic"]/a/img/@src')[0].strip()

        book_info_dict = {
            'title': title,
            'src_title': src_title,
            'author': author,
            'score': score,
            'eval_number': eval_number,
            'cover_url': cover_url,
            'tags': tags,
            'book_intro': book_intro,
            'author_intro': author_intro
        }
        print("书籍豆瓣url", book_url)
        book_info = BookInfo(book_info_dict)
        return book_info


if __name__ == '__main__':
    book_name = input("请输入书名：")
    #     cat = input(
    #         '''
    # 1 Java
    # 2 Python
    # 3 C
    # 4 数据库
    # 5 JavaScript
    #
    # 请输入书的类别:'''
    #     )
    book = get_book(book_name)
    print(book.to_string())
